import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import WindiCSS from 'vite-plugin-windicss'
import { vueI18n } from '@intlify/vite-plugin-vue-i18n'
import vueJsx from '@vitejs/plugin-vue-jsx'
import { join } from 'path'
import { writeFileSync } from 'fs'
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'

// 默认读取生产条件下的环境变量
const antPrefix = loadEnv('product', process.cwd())['VITE_ANTD_PREFIX']

export default defineConfig({
    base: '/app_50000005/',
    plugins: [
        vue(),
        vueJsx(),
        WindiCSS(),
        vueI18n({
            include: resolve(__dirname, './src/locales/**'),
            defaultSFCLang: 'yml'
        }),
        (function () {
            let basePath = ''
            return {
                name: 'vite:micro-app',
                apply: 'build',
                configResolved(config) {
                    basePath = `${config.base}${config.build.assetsDir}/`
                },
                writeBundle(options, bundle) {
                    for (const chunkName in bundle) {
                        if (Object.prototype.hasOwnProperty.call(bundle, chunkName)) {
                            const chunk = bundle[chunkName]
                            if (chunk.fileName && chunk.fileName.endsWith('.js')) {
                                chunk.code = chunk.code.replace(
                                    /(from|import\(?)(\s*['"])(\.\.?\/)/g,
                                    (all, $1, $2, $3) => {
                                        const u = new URL($3, 'http://tmp.com' + basePath)
                                        // return all.replace($3, new URL($3, basePath));
                                        return all.replace($3, u.pathname)
                                    }
                                )
                                const fullPath = join(options.dir, chunk.fileName)
                                writeFileSync(fullPath, chunk.code)
                            }
                        }
                    }
                }
            }
        })(),
        createSvgIconsPlugin({
            iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
            svgoOptions: true,
            // default
            symbolId: 'icon-[dir]-[name]'
        })
    ],
    resolve: {
        alias: [{ find: '@', replacement: resolve(__dirname, 'src') }]
    },
    css: {
        preprocessorOptions: {
            less: {
                javascriptEnabled: true,
                modifyVars: {
                    'ant-prefix': antPrefix,
                    hack: `true; @import (reference) "${resolve('src/design/custom-theme.less')}";`
                },
                additionalData: `@import "${resolve(__dirname, 'src/design/base.less')}";`
            }
        }
    },
    server: {
        port: 3300,
        proxy: {
            '/solution-crm/api/': {
                target: 'http://ppm-stage.allintechinc.com/',
                changeOrigin: true,
                ws: true,
                secure: false
                // rewrite: path => path.replace(/^\/dev-api/, '')
            }
        }
    },
    build: {
        rollupOptions: {
            output: {
                manualChunks(id) {
                    if (id.includes('node_modules')) {
                        const names = id.split('node_modules/')
                        const lastPath = names[names.length - 1]
                        return '_lib_' + lastPath.split('/')[0].replace('@', '_')
                    }
                }
            }
        }
    }
})
